import React from "react";
import "./newProgress.scss";
import { HashRouter as Router, Route, Link } from "react-router-dom";
import AreaData from "../../../component/areaData/areaData.js"; //地址库
import utils from "../../../utils/utils";
import cookie from "react-cookies";
import moment from "moment";
import BreadcrumbNav from "../../../component/breadcrumb/breadcrumb.js";
import {
  Steps,
  Col,
  Row,
  message,
  Form,
  Input,
  Button,
  Checkbox,
  DatePicker,
  Select,
  Upload,
  Modal,
} from "antd";
import {
  LoadingOutlined,
  PlusOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { fileUpload } from "../../../api/extra";
import {
  getUserPositionInfo,
  addUserAndAuthority,
  updUserAndAuthority,
  getAllAccounnt,
} from "../../../api/accountManage";
import { addProjectFirstStep } from "../../../api/hardwareCenter";
import store from "../../../redux/store";

const { Step } = Steps;
const { Option } = Select;

class newProgress extends React.Component {
  Forms = React.createRef();
  constructor(props) {
    super(props);
    
    this.state = {
      loading: false,
      activeUlId: "133",
      previewVisible: false,
      previewImage: "",
      previewTitle: "",
      fileList:props.OptionOneStep.fileList || [
        
      ],
      fileList2:props.OptionOneStep.fileList2 ||  [],
      projectName: props.OptionOneStep.projectName || "",
      allAddress:props.OptionOneStep.allAddress ||"",
      signDate: props.OptionOneStep.signDate || "",
      project_phase: props.OptionOneStep.project_phase || "",
      admin_phone:props.OptionOneStep. admin_phone || "",
      lane_count: props.OptionOneStep.lane_count || "",
      lane_out_count: props.OptionOneStep.lane_out_count || "",
      lane_in_count: props.OptionOneStep.lane_in_count || "",
      IP_info:props.OptionOneStep.IP_info || [],
      pro_review: props.OptionOneStep.pro_review || "",
      pro_creater: store.getState().addRole,
      pro_creater_id: store.getState().addId,
      admin_account:props.OptionOneStep. admin_account || "" ,
      dataSource:props.OptionOneStep.dataSource ||  [],
      pro_review_id: props.OptionOneStep.pro_review_id || "",
      ProComy:props.OptionOneStep.ProComy || "",
    };
  }

  componentDidMount() {
    this.getAllAccounnt();
    this.Forms.current.setFieldsValue({
      pro_review_id: this.props.OptionOneStep.pro_review_id || "",
    })
    this.setState(
      {
        activeUlId: "1",
      },
      () => {
        console.log(this.state.activeUlId);
        console.log(process.env.API_URL);
      }
    );
    console.log('this.props',this.props)
  }

  //获取账户信息
  getAllAccounnt = () => {
    let post_data = {
      auth_token: cookie.load("station_console_setting_web_login").auth_token,
      state:1
    };
    getAllAccounnt(post_data).then((res) => {
      console.log(res);
      if (res.code == 0) {
        this.setState({
          dataSource: res.data,
        });
      }
    });
  };
  // 下一步
  nextStep = () => {
    // let value ={
    //     'auth_token':cookie.load('station_console_setting_web_login').auth_token,
    //     'project_name':this.state.projectName,
    //     'province':this.state.allAddress[0],
    //     'city':this.state.allAddress[1],
    //     'area':this.state.allAddress[2],
    //     'address':this.state.allAddress[3],
    //     'sign_time':this.state.signDate,
    //     'project_phase':this.state.project_phase,
    //     'user_admin_account':this.state.admin_phone,
    //     'lane_count':this.state.lane_count,
    //     'lane_out_count':this.state.lane_out_count,
    //     'lane_in_count':this.state.lane_in_count,
    //     'ip':this.state.IP_info,
    //     'review_u_name':this.state.pro_review,
    //     'review_u_id':this.state.pro_review_id,
    //     'create_u_name':this.state.pro_creater,
    //     'create_u_id':this.state.pro_creater_id,
    //     'factory_img_ids':this.state.fileList,
    //     'project_company':this.state.ProComy
    // }
    // console.log(value)
    // addProjectFirstStep().then(res=>{
    //     console.log(res)
    // })
    // cookie.save('step1',,{path:'/ '})
        // cookie.save('step1',,{path:'/ '}) 
    // cookie.save('step1',,{path:'/ '})
  };

  onFinish = (values) => {
    console.log("Success:", values);
  };

  cancel = () => {
    let _this = this;
    console.log("cancel");
    window.location.href='/index/hardwareCenter/programConfig'
    
  };

  getBase64 = (file) => {
    console.log("getbase64", file);
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  };

  handleCancel = () => this.setState({ previewVisible: false });

  handlePreview = async (file) => {
    console.log(file);
    if (!file.url && !file.preview) {
      file.preview = await this.getBase64(file.originFileObj);
    }

    this.setState({
      previewImage: file.url || file.preview,
      previewVisible: true,
      previewTitle:
        file.name || file.url.substring(file.url.lastIndexOf("/") + 1),
    });
  };
  // handleChange = ({ fileList }) => this.setState({ fileList },()=>{console.log(fileList)});

  // beforeUpload = (file) => {
  //     console.log('file',file)
  //     const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  //     if (!isJpgOrPng) {
  //         message.error('请上传 JPG/PNG 格式的文件!');
  //     }
  //     const isLt2M = file.size / 1024 / 1024 < 2;
  //     if (!isLt2M) {
  //         message.error('图片必须小于 2MB!');
  //     }
  //     return isJpgOrPng && isLt2M;
  // }

  uploadHeadImg = (info) => {
    const { fileList } = this.state;
    // console.log('info',info.file)
    let post_data = {
      auth_token: cookie.load("station_console_setting_web_login").auth_token,
      file: info.file,
      file_type: 1,
    };
    console.log(post_data);
    fileUpload(post_data).then((res) => {
      console.log(res);
      fileList.push({
        url: res.data.full_url,
        status: "done",
        uid: res.data.attach_id,
      });

      this.setState(
        {
          fileList,
        },
        () => {
          console.log(fileList);
        }
      );
    });
  };
  // remove-file
  removefile = (file) => {
    const {fileList} = this.state

    fileList.forEach((item, index) => {
        if (file.uid == item.uid) {
            fileList.splice(index, 1);
        }
    });
    this.setState({
        fileList: fileList,
    })
  };
  // remove-file
  removefile2 = (file) => {
    const {fileList2} = this.state

    fileList2.forEach((item, index) => {
        if (file.uid == item.uid) {
            fileList2.splice(index, 1);
        }
    });
    this.setState({
        fileList2: fileList2,
    })
  };

  //设置所选地址
  getChangeAdress = (val, selectedOptions, name) => {
    this.setState({
      [name]: val,
    });
  };
  //地点选择
  // getChangeStart = (val, selectedOptions) => {
  // 	console.log(val, selectedOptions)
  // 	this.setState({
	// 	this.setState({ 
  // 	this.setState({
  //         allAddress: val,
  //     })
  // }
  //
    // 
  //
  onChangedate = (date, dateString) => {
    console.log(date, dateString);
    this.setState(
      {
        signDate: dateString,
      },
      () => {
        console.log(this.state.signDate);
      }
    );
  };
  // 添加项目IP
  handleAdd = () => {
    const { IP_info } = this.state;
    IP_info.push({
      IP: "",
      
      id: IP_info.length + 1,
    });
    this.setState({
      IP_info,
    });
    console.log(IP_info);
  };
  // 删除
  handleDelete = (el) => {
    const { IP_info } = this.state;
    IP_info.splice(el, 1);
    IP_info.map((item, index) => {
      item.num = index + 1;
      item.id = index + 1;
    });
    this.setState({
      IP_info,
    });
    console.log(IP_info);
  };
  // input/添加IP
  setName = (index, e) => {
    const { IP_info } = this.state;
    IP_info[index].IP = e.target.value;
    this.setState({
      IP_info,
    });
    console.log(IP_info);
  };

  beforeUpload2 = (file) => {
    const fType = file.name.slice(file.name.lastIndexOf(".") + 1);
    const isXLS =
      fType === "xls" ||
      fType === "xlsx" ||
      fType === "docx" ||
      fType === "pdf" ||
      fType === "doc";
    if (!isXLS) {
      message.error("请选择 xls、xlsx、docx、pdf、doc 类型的文件");
    }
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error("请上传小于10MB的文件!");
    }
    return isXLS && isLt10M;
  };

  uploadHeadImg2 = (info) => {
    const { fileList2 } = this.state;

    let post_data = {
      auth_token: cookie.load("station_console_setting_web_login").auth_token,
      file: info.file,
      file_type: 2,
    };
    console.log(post_data);
    fileUpload(post_data).then((res) => {
      console.log(res);
      fileList2.push({
        name: info.file.name,
        url: res.data.full_url,
        status: "done",
        uid: res.data.attach_id,
      });

      this.setState(
        {
          fileList2,
        },
        () => {
          info.onSuccess();
          info.file.uid = res.data.attach_id;
          console.log(fileList2);
          console.log("info", info.file);
        }
      );
    });
  };
  
  // 选中
  selected = (val) => {
    console.log(val, "parttt");
    this.setState({
      pro_review: val.label,
      pro_review_id: val.value,
    });
  };

  render() {
    const {
      data,
      activeUlId,
      dataSource,
      current,
      steps,
      pro_creater_id,
      previewVisible,
      previewImage,
      admin_account,
      pro_creater,
      pro_review,
      fileList,
      fileList2,
      previewTitle,
      lane_count,
      IP_info,
      lane_out_count,
      lane_in_count,
      admin_phone,
      loading,
      project_phase,
      imageUrl,
      projectName,
      ProComy,
      allAddress,
      signDate,
      pro_review_id
    } = this.state;

    const { next } = this.props;
    const uploadButton = (
      <div>
        <PlusOutlined />
        <div style={{ marginTop: 8 }}>Upload</div>
      </div>
    );

    return (
      <Router>
        <div className="addNewPro" id="ContentMainList">
          {/* <Row className="topbox">
                        <Col className="topPro" span={24}>
                            <div className="box">
                                <p className="circle1"></p>
                                <p>项目基本信息</p>
                            </div>
                            <div className="line">
                                .................................
                            </div>
                            <div className="box">
                                <p className="circle"></p>
                                <p>项目状态</p>
                            </div>
                            <div className="line">
                                .................................
                            </div>
                            <div className="box">
                                <p className="circle"></p>
                                <p>设备配备</p>
                            </div>
                        </Col>
                    </Row> */}

          <Row className="steps-action">
            <Col span={24}>
              <div className="tipss">
                <span className="blue"></span>
                <span>项目设备配备</span>
              </div>
              <Form
                ref={this.Forms}
                name="basic"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 14 }}
                initialValues={{ 
                  projectName: projectName,
                  ProComy: ProComy,
                  allAddress: allAddress,
                  signDate: signDate ? moment(signDate) : "",
                  project_phase: project_phase,
                  admin_phone: admin_phone,
                  lane_count: lane_count,
                  lane_in_count: lane_in_count,
                  lane_out_count: lane_out_count,
                 }}
                autoComplete="off"
                onFinish={this.onFinish.bind(this)}
              >
                <Form.Item
                  label="项目名称"
                  name="projectName"
                  rules={[{ message: "请输入项目名称!" }]}
                >
                  <Input
                    onChange={(e) => {
                      this.setState({ projectName: e.currentTarget.value });
                    }}
                  />
                </Form.Item>

                <Form.Item
                  label="项目公司"
                  name="ProComy"
                  rules={[{ message: "请输入项目公司!" }]}
                >
                  <Input
                    value={ProComy}
                    onChange={(e) => {
                      this.setState({ ProComy: e.currentTarget.value });
                    }}
                  />
                </Form.Item>

                <Form.Item
                  label="项目地址"
                  name="allAddress"
                  rules={[{ message: "请输入项目地址!" }]}
                >
                  <AreaData
                    placeholder="省/市/县区/详细地址"
                    msg={allAddress}
                    getChangeAreaData={(val, selectedOptions) =>
                      this.getChangeAdress(val, selectedOptions, "allAddress")
                    }
                  />
                </Form.Item>

                <Form.Item label="签约时间" name="signDate">
                  <DatePicker
                    showTime
                    onChange={this.onChangedate.bind(this)}
                    style={{ width: "100%" }}
                  />
                </Form.Item>

                <Form.Item
                  label="当前项目阶段"
                  name="project_phase"
                  rules={[{ message: "请输入项目当前阶段!" }]}
                >
                  <Select
                    allowClear
                    value={project_phase}
                    onChange={(e) => {
                      this.setState({ project_phase: e });
                    }}
                  >
                    <Option value="1">厂区建设阶段</Option>
                    <Option value="2">道闸施工阶段</Option>
                    <Option value="3">软件调试阶段</Option>
                    <Option value="4">维保期内</Option>
                    <Option value="5">服务到期</Option>
                  </Select>
                </Form.Item>

                <Form.Item
                  label="管理员账号"
                  name="admin_phone"
                  rules={[{ message: "请输入项目管理员账号!" }]}
                >
                  <Input
                    value={admin_phone}
                    onChange={(e) => {
                      this.setState({ admin_phone: e.currentTarget.value });
                    }}
                    placeholder="请输入项目管理员手机号"
                    style={{ width: "150px" }}
                  />
                  <span
                    style={{
                      color: "##A4A4A4",
                      fontSize: "12px",
                      marginLeft: "15px",
                    }}
                  >
                    注：此手机号为[用户系统]的管理员登录账号,请谨慎填写
                  </span>
                </Form.Item>

                <Form.Item label="车道数">
                  <Form.Item
                    label=""
                    name="lane_count"
                    style={{
                      display: "inline-block",
                      width: "calc(30% - 12px)",
                      marginRight: "10px",
                    }}
                    rules={[{ message: "请输入项目车道数辆!" }]}
                  >
                    <Input
                      value={lane_count}
                      onChange={(e) => {
                        this.setState({ lane_count: e.currentTarget.value });
                      }}
                    />
                  </Form.Item>
                  <Form.Item
                    label=""
                    name="lane_in_count"
                    style={{
                      display: "inline-block",
                      width: "calc(22% - 8px)",
                    }}
                    rules={[{ message: "入站车道数!" }]}
                  >
                    <Input
                      value={lane_in_count}
                      onChange={(e) => {
                        this.setState({ lane_in_count: e.currentTarget.value });
                      }}
                    />
                  </Form.Item>
                  <span className="defaultTip">进</span>
                  <Form.Item
                    label=""
                    name="lane_out_count"
                    style={{
                      display: "inline-block",
                      width: "calc(22% - 8px)",
                    }}
                    rules={[{ message: "出站车道数!" }]}
                  >
                    <Input
                      value={lane_out_count}
                      onChange={(e) => {
                        this.setState({
                          lane_out_count: e.currentTarget.value,
                        });
                      }}
                    />
                  </Form.Item>
                  <span className="defaultTip">出</span>
                </Form.Item>

                <Form.Item label="项目IP" name="IP_info">
                  <span className="tipIP">IP地址1：-- . -- . -- . --</span>
                  <span className="defaultTip">
                    IP地址分为4段，每段范围为0～255的整数
                  </span>
                  <Button
                    onClick={this.handleAdd.bind(this)}
                    type="primary"
                    style={{
                      width: "60px",
                      padding: "10px",
                      lineHeight: "3px",
                      marginLeft: "30px",
                    }}
                  >
                    添加IP
                  </Button>
                  {IP_info.map((item, index) => (
                    <Row className="fre" key={index}>
                      <Col span={24}>
                        <span className="fre_name">项目IP{index + 1}</span>
                        <Input
                          style={{ width: "220px" }}
                          placeholder="请输入项目IP，例：--.--.--.--"
                          value={item.IP}
                          onChange={this.setName.bind(this, index)}
                        ></Input>
                        {index == 0 ? (
                          ""
                        ) : (
                          <div
                            className="dele_img"
                            onClick={this.handleDelete.bind(this, index)}
                          ></div>
                        )}
                      </Col>
                    </Row>
                  ))}
                </Form.Item>

                <Form.Item
                  label="厂区图"
                  name="fileList"
                  rules={[{ message: "默认登录的项目管理员账号!" }]}
                >
                  <Upload
                    // action={`${process.env.API_URL}/internal_public/attach/fileUpload`}
                    customRequest={this.uploadHeadImg.bind(this)}
                    listType="picture-card"
                    showUploadList={{ showRemoveIcon: true }}
                    fileList={fileList}
                    onRemove={this.removefile}   
                    onPreview={this.handlePreview.bind(this)}
                    // onChange={this.handleChange.bind(this)}
                  >
                    {fileList.length >= 10 ? null : uploadButton}
                  </Upload>
                  <span className="defaultTip">（最多支持10张图片的上传）</span>
                </Form.Item>

                <Form.Item label="合同附件" name="fileList2">
                  <Upload
                    customRequest={this.uploadHeadImg2.bind(this)}
                    beforeUpload={this.beforeUpload2.bind(this)}
                    showUploadList={{ showRemoveIcon: true }}
                    fileList={fileList2}
                    onRemove={this.removefile2}
                  >
                    <Button
                      style={{ display: "inline-block", width: "100px" }}
                      icon={<UploadOutlined />}
                    >
                      附件上传
                    </Button>
                  </Upload>
                </Form.Item>

                <Form.Item
                  label="项目创建人"
                  name="pro_creater"
                  rules={[{ message: "请输入项目创建人!" }]}
                >
                  <span
                    style={{
                      display: "inline-block",
                      background: "#f4f4f4",
                      padding: "10px",
                    }}
                  >
                    {pro_creater}
                  </span>
                  {/* <Input value={pro_creater} onChange={(e)=>{this.setState({pro_creater:e.currentTarget.value})}} /> */}
                </Form.Item>

                  {/* pro_review_id:  */}
                <Form.Item label="项目复核人" name="pro_review_id" >
                  {console.log(pro_review_id)}
                  <Select
                    style={{ width: "200px" }}
                    defaultValue={{value:pro_review_id}}
                    size="small"
                    placeholder="请选择用户所属部门"
                    labelInValue
                    allowClear
                    onChange={this.selected.bind(this)}
                  >
                    {dataSource.map((item, index) => (
                      <Option key={index} value={item.id}>{item.user_name}</Option>
                    ))}
                  </Select>
                </Form.Item>

                <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                  <Button
                    type="primary"
                    onClick={this.cancel.bind(this)}
                    style={{
                      display: "inline-block",
                      width: "120px",
                      marginRight: "12px",
                    }}
                  >
                    取消
                  </Button>
                  <Button
                    onClick={() => next(this.state)}
                    type="primary"
                    style={{
                      display: "inline-block",
                      width: "120px",
                      marginRight: "12px",
                    }}
                  >
                    <Link >下一步</Link>
                  </Button>
                </Form.Item>
              </Form>
            </Col>
          </Row>

          <Modal
            visible={previewVisible}
            title={previewTitle}
            footer={null}
            onCancel={this.handleCancel.bind(this)}
          >
            <img alt="example" style={{ width: "100%" }} src={previewImage} />
          </Modal>
        </div>
      </Router>
    );
  }
}

export default newProgress;
